{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "22a0b426",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input: 101, Accepted: True\n",
      "Input: 011, Accepted: False\n"
     ]
    }
   ],
   "source": [
    "class DFA:\n",
    "    def __init__(self, states, alphabet, transition_function, start_state, accept_states):\n",
    "        self.states = states\n",
    "        self.alphabet = alphabet\n",
    "        self.transition_function = transition_function\n",
    "        self.start_state = start_state\n",
    "        self.accept_states = accept_states\n",
    "\n",
    "    def accepts(self, input_string):\n",
    "        current_state = self.start_state\n",
    "        for symbol in input_string:\n",
    "            if symbol in self.alphabet:\n",
    "                current_state = self.transition_function[current_state][symbol]\n",
    "            else:\n",
    "                return False\n",
    "        return current_state in self.accept_states\n",
    "\n",
    "# 定义一个DFA，识别以'01'结尾的字符串\n",
    "states = {'q0', 'q1', 'q2'}\n",
    "alphabet = {'0', '1'}\n",
    "transition_function = {\n",
    "    'q0': {'0': 'q0', '1': 'q1'},\n",
    "    'q1': {'0': 'q2', '1': 'q0'},\n",
    "    'q2': {'0': 'q1', '1': 'q2'}\n",
    "}\n",
    "start_state = 'q0'\n",
    "accept_states = {'q2'}\n",
    "\n",
    "dfa = DFA(states, alphabet, transition_function, start_state, accept_states)\n",
    "\n",
    "# 示例使用\n",
    "input_string = \"101\"  # 应该被接受\n",
    "print(f\"Input: {input_string}, Accepted: {dfa.accepts(input_string)}\")\n",
    "\n",
    "input_string = \"011\"  # 不应该被接受\n",
    "print(f\"Input: {input_string}, Accepted: {dfa.accepts(input_string)}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46650d0a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
